// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database()
const $c$ = cloud.database().command

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  switch (event.action) {
    case "createQRCode":
      return createQRCode(event)
      break
    case "siteSearch":
      return getSiteSearchData(event)
      break
    case "getMonthVisitData":
      return getMonthVisitData(event)
      break
    case "getUserPortrait":
      return getUserPortrait(event)
      break
    case "getWeRunData":
      return getWeRunData(event)
      break
  }
  return '参数错误'
}

// 小程序内部搜索API提供针对页面的查询能力
async function getSiteSearchData(event) {
  let data = {
    keyword: event.siteSearch,
    nextPageInfo: ''
  }
  console.log(data)
  const result = await cloud.openapi.search.siteSearch(data)
  return result
}

// 生成小程序二维码
async function createQRCode(event) {
  const result = await cloud.openapi.wxacode.createQRCode({
    path: event.path,
    width: 430
  })
  return result
}

// 获取小程序月数据
async function getMonthVisitData() {
  var nowMonth = new Date().getMonth(); //当前月 
  var nowYear = new Date().getFullYear(); //当前年 
  var monthStartDate = new Date(nowYear, nowMonth, 1);
  var monthEndDate = new Date(nowYear, nowMonth + 1, 0);
  let preDate = monthStartDate.toFormat("yyyyMMdd");
  let nowDate = monthEndDate.toFormat("yyyyMMdd");
  console.log(preDate)
  console.log(nowDate)
  const result = await cloud.openapi.analysis.getMonthlyVisitTrend({
    beginDate: "20200801",
    endDate: "20200831"
  })
  return result
}

// 获取小程序用户的画像分布数据
async function getUserPortrait() {
  const result = await cloud.openapi.analysis.getUserPortrait({
    beginDate: '20200901',
    endDate: '20200907'
  })
  return result
}

// 微信运动数据
async function getWeRunData(event) {
  return event.weRunData;
}

Date.prototype.toFormat = function (fmt) {
  var o = {
    'M+': this.getMonth() + 1,
    'd+': this.getDate(),
    'H+': this.getHours(),
    'm+': this.getMinutes(),
    's+': this.getSeconds(),
    'S+': this.getMilliseconds()
  };
  //因为date.getFullYear()出来的结果是number类型的,所以为了让结果变成字符串型，下面有两种方法：
  if (/(y+)/.test(fmt)) {
    //第一种：利用字符串连接符“+”给date.getFullYear()+''，加一个空字符串便可以将number类型转换成字符串。
    fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
  }
  for (var k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) {
      //第二种：使用String()类型进行强制数据类型转换String(date.getFullYear())，这种更容易理解。
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (('00' + o[k]).substr(String(o[k]).length)));
    }
  }
  return fmt;
};